package bblnamed

import (
	"encoding/json"
	"fmt"
	"github.com/facebookgo/httpcontrol"
	"io/ioutil"
	"net/http"
	"os"
	"time"
)

var http_client = &http.Client{
	Transport: &httpcontrol.Transport{
		RequestTimeout: 0 * time.Second,
		MaxTries:       3,
	},
}

func Delete(addr, path string) error {
	req, err := http.NewRequest("DELETE", fmt.Sprintf("http://%v%v", addr, path), nil)
	if err != nil {
		return err
	}
	resp, err := http_client.Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	log.Debug("DELETE\t", req, "\t\n", resp)
	if resp.StatusCode == 200 {
		return nil
	}
	return fmt.Errorf("%v %v", resp.StatusCode, resp.Status)
}

func Trancate(addr, path string) error {
	req, err := http.NewRequest("TRUNCATE", fmt.Sprintf("http://%v%v", addr, path), nil)
	if err != nil {
		return err
	}
	resp, err := http_client.Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	log.Debug("TRUNCATE\t", req, "\t\n", resp)
	if resp.StatusCode == 200 {
		return nil
	}
	return fmt.Errorf("%v %v", resp.StatusCode, resp.Status)
}

func Purge(host, addr, path string) error {
	req, err := http.NewRequest("PURGE", fmt.Sprintf("http://%v%v", addr, path), nil)
	if err != nil {
		return err
	}
	if host != "" {
		req.Header.Set("X-Host", host)
	}
	resp, err := http_client.Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	log.Debug("PURGE\t", req, "\t\n", resp)
	if resp.StatusCode == 200 {
		return nil
	}
	return fmt.Errorf("%v %v", resp.StatusCode, resp.Status)
}

func GetJob(addr, path string) (*Job, error) {
	req, err := http.NewRequest("GET_JOB", fmt.Sprintf("http://%v%v", addr, path), nil)
	if err != nil {
		return nil, err
	}
	resp, err := http_client.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	data, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}
	job := Job{}
	err = json.Unmarshal(data, &job)
	if err != nil {
		return nil, err
	}
	return &job, nil
}

func PostFile(addr, path, file string) (writen int64, err error) {
	f, err := os.OpenFile(file, os.O_RDONLY, os.ModePerm)
	if err != nil {
		return 0, err
	}
	defer f.Close()
	fi, err := f.Stat()
	if err != nil {
		return 0, err
	}
	req, err := http.NewRequest("PUT", fmt.Sprintf("http://%v%v", addr, path), f)
	if err != nil {
		return 0, err
	}
	req.Header.Add("Content-Type", "application/octet-stream")
	req.ContentLength = fi.Size()
	resp, err := http_client.Do(req)
	if err != nil {
		return 0, err
	}
	defer resp.Body.Close()
	log.Debug("\t", req, "\t\n", resp)
	return fi.Size(), nil
}
